package NetWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;

    public UdpEchoClient(String severIp , int serverPort) throws SocketException {
        socket = new DatagramSocket();
        //Ip和端口号 需要额外记录,以备后面使用
        this.severIp = severIp;
        this.severPort = serverPort;
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的请求: ");
            //1.从控制台读取用户输入
            String request = scanner.next();
            //2.构造请求并发送
            // 构造请求数据的时候, 不光要有数据 , 还要有 "目标"
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes() , 0 , request.getBytes().length,//获取字符数长度
                    InetAddress.getByName(severIp),severPort);
            socket.send(requestPacket);
            //3.读取响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.将显示响应到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());//获取字节数
            System.out.println(response);
        }

    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
